package com.ay.java.proxy.cglibproxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author: ay
 * @Date: 2021/6/11
 * @Description:
 **/
public class CglibProxy implements MethodInterceptor {

    private Object target;

    /**
     * 创建代理对象
     * @param target 被代理的对象
     * @return
     */
    public Object createProxy(Object target){
        //创建增强器
        Enhancer enhancer = new Enhancer();
        //确定要增强的类，指定其父类
        enhancer.setSuperclass(target.getClass());
        //设置回调函数
        enhancer.setCallback(this);
        //返回代理类
        return enhancer.create();
    }

    /**
     *
     * @param o
     * @param method
     * @param objects
     * @param methodProxy
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("【cglib动态代理】模拟权限检查");
        Object obj = methodProxy.invokeSuper(o,objects);
        System.out.println("【cglib动态代理】模拟记录日志");
        return obj;
    }
}
